﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Xml.Linq;
using Grundy.Common;
using Grundy.Message;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Grundy.CryptographicServices.Tests
{
    [TestClass]
    public class RsaProviderTests
    {
        private string aliceKeyPair;
        private string alicePublicKey;
        
        private const string MESSAGE = "This is the test data!";

        [TestInitialize]
        public void Setup()
        {
            var provider = new RSACryptoServiceProvider(1024);
            aliceKeyPair = provider.ToXmlString(true);
            alicePublicKey = provider.ToXmlString(false);
        }
        
        [TestMethod]
        public void Should_Sign_And_Verify_Data()
        {
            var payload = new ProcessorIdentifier { Value = MESSAGE };
            var rsaProviderForAlice = new RsaProvider(aliceKeyPair);
            var rsaProviderForBob = new RsaProvider(alicePublicKey);
            
            var container = rsaProviderForAlice.Sign(payload);
            var verifiedPayload = rsaProviderForBob.Verify<Identifier>(container);
            Assert.AreEqual(verifiedPayload.Value, MESSAGE);
        }

        [TestMethod]
        public void Should_Not_Sign_And_Verify_Data()
        {
            var payload = new ProcessorIdentifier { Value = MESSAGE };
            var rsaProviderForAlice = new RsaProvider(aliceKeyPair);
            var rsaProviderForBob = new RsaProvider(alicePublicKey);

            var container = rsaProviderForAlice.Sign(payload);
            container.Signature = container.Signature.Replace('1', '2');
            var verifiedPayload = rsaProviderForBob.Verify<Identifier>(container);
            Assert.IsNull(verifiedPayload);
        }

        [TestMethod]
        public void Should_Not_Be_Able_To_Verify_Container()
        {
            var payload = new ProcessorIdentifier { Value = MESSAGE };
            var rsaProviderForAlice = new RsaProvider(aliceKeyPair);
            var rsaProviderForBob = new RsaProvider(alicePublicKey);

            var container = rsaProviderForAlice.Sign(payload);
            container.Provider = "{0},{1},{2}".FormatWith("Sha256MacProvider",Guid.NewGuid(), "Dev_Customer");
            var verifiedPayload = rsaProviderForBob.Verify<Identifier>(container);
            Assert.IsNull(verifiedPayload);

            container.Provider = "{0},{1},{2}".FormatWith("Sha256MacProvider", Guid.NewGuid(), null);
            verifiedPayload = rsaProviderForBob.Verify<Identifier>(container);
            Assert.IsNull(verifiedPayload);

            container.Provider = "{0}".FormatWith("Sha256MacProvider", Guid.NewGuid());
            verifiedPayload = rsaProviderForBob.Verify<Identifier>(container);
            Assert.IsNull(verifiedPayload);
        }
    }
}
